package com.chain.BrotherExchange.im.ui;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.chain.BrotherExchange.BuildConfig;
import com.chain.BrotherExchange.C;
import com.chain.BrotherExchange.R;
import com.chain.BrotherExchange.data.DataRepository;
import com.chain.BrotherExchange.data.model.ChattingRecords;
import com.chain.BrotherExchange.data.model.LegalTenderOrderList;
import com.chain.BrotherExchange.im.IMWebSocket;
import com.chain.BrotherExchange.im.entity.ReceiveMessage;
import com.chain.BrotherExchange.im.model.Message;
import com.chain.BrotherExchange.ui.adapter.TextWatcherAdapter;
import com.chain.BrotherExchange.ui.core.AbsNetworkStateActivity;
import com.chain.BrotherExchange.utils.Androids;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;

public class WebSocketActivity extends AbsNetworkStateActivity {

    public static void launch(Context context, Serializable serializable) {
        context.startActivity(new Intent(context, WebSocketActivity.class)
                .putExtra(C.EXTRA_TRANSACTION_ORDER_DETAILS, serializable)
        );
    }

    @Bind(R.id.title_text) TextView mTitleTextView;
    @Bind(R.id.message_list) RecyclerView mMessageList;
    @Bind(R.id.message_edit) EditText mMessageEditText;
    @Bind(R.id.send_button) ImageButton mSendMessageButton;
    @Bind(R.id.arrow_back_image) AppCompatImageView mArrowBackImage;

    private MessageAdapter mMessageAdapter;
    private int uid = Androids.LocalConfig.getUid();
    private String token = Androids.LocalConfig.getToken();

    @Override
    public int getTitleLayoutRes() {
        return R.layout.layout_default_title_bar;
    }

    @Override
    protected int getLayoutID() {
        return R.layout.activity_web_socket;
    }

    @Override
    protected void initActions() {
        // 订单信息
        LegalTenderOrderList.DataBean.ListBean orderInfo = (LegalTenderOrderList.DataBean.ListBean)
                getIntent().getSerializableExtra(C.EXTRA_TRANSACTION_ORDER_DETAILS);

        // 聊天列表
        mMessageList.setItemAnimator(new DefaultItemAnimator());
        mMessageAdapter = new MessageAdapter(mMessageList);
        mMessageList.setAdapter(mMessageAdapter);

        // 默认不可点击
        mSendMessageButton.setEnabled(false);

        // 输入监听
        mMessageEditText.addTextChangedListener(new TextWatcherAdapter(s -> {
            if (s.length() > 0) {
                if (!mSendMessageButton.isEnabled()) {
                    mSendMessageButton.setEnabled(true);
                    mSendMessageButton.setImageResource(R.mipmap.mq_ic_send_icon_white);
                    mSendMessageButton.setBackgroundResource(R.drawable.shape_oval_active);
                }
            } else {
                mSendMessageButton.setEnabled(false);
                mSendMessageButton.setImageResource(R.mipmap.mq_ic_send_icon_grey);
                mSendMessageButton.setBackgroundResource(R.drawable.shape_oval_normal);
            }
        }));

        // 标题
        String toUsername, myUsername;
        if (orderInfo.getBuy_id() == uid) {
            toUsername = orderInfo.getSell_name();
            myUsername = orderInfo.getBuy_name();
        } else {
            toUsername = orderInfo.getBuy_name();
            myUsername = orderInfo.getSell_name();
        }
        mTitleTextView.setText("与" + toUsername + "聊天中");
        mArrowBackImage.setOnClickListener(v -> onBackPressed());

        // 初始化聊天
        initWebSocket(
                BuildConfig.WEB_SOCKET_URI + orderInfo.getOrder_id() + orderInfo.getSell_id() + orderInfo.getBuy_id(),
                myUsername,
                orderInfo.getOrder_id(),
                orderInfo.getSell_id(),
                orderInfo.getBuy_id()
        );

        // 初始化聊天记录
        initChatRecord(orderInfo.getOrder_id());
    }

    private void initChatRecord(String orderId) {
        DataRepository.get().chattingRecords(uid, token, orderId, result -> {
            List<ChattingRecords.DataBean> recordList = result.getData();
            List<Message> messageList = new ArrayList<>();
            if (recordList != null){
                for (ChattingRecords.DataBean record : recordList) {
                    if (record.getUid() == uid) {
                        messageList.add(new Message(Message.SEND_TYPE, record.getContent()));
                    } else {
                        messageList.add(new Message(Message.RECEIVE_TYPE, record.getContent()));
                    }
                }

                mMessageAdapter.addMessageList(messageList);
            }
        });
    }

    private void initWebSocket(String uri, String username, String orderId, int sellerId, int buyerId) {
        loadingNetwork();

        IMWebSocket imWebSocket = new IMWebSocket(uri, BuildConfig.WEB_SOCKET_PORT);
        imWebSocket.connection(status ->
                imWebSocket.authentication(token, uid, username, orderId, sellerId, buyerId,
                        this::successNetwork)
        );

        // 接收消息
        imWebSocket.setReceiveCallback(this::analysisReceiveMessage);

        // 发送消息
        mSendMessageButton.setOnClickListener(v -> {
            String message = mMessageEditText.getText().toString().trim();
            imWebSocket.sendText(message);
            mMessageEditText.setText(null);
        });
    }

    private void analysisReceiveMessage(ReceiveMessage receiveMessage) {
        if (receiveMessage.getData().getUid() != uid) {
            mMessageAdapter.addMessage(new Message(Message.RECEIVE_TYPE, receiveMessage.getData().getContent()));
        } else {
            mMessageAdapter.addMessage(new Message(Message.SEND_TYPE, receiveMessage.getData().getContent()));
        }
    }

    @Override
    public void onAnewRequest() {

    }
}
